<template>
  <div class="advanced-search__product-search">
    <el-select
      :value="selectValue"
      value-key="id"
      filterable
      remote
      clearable
      :placeholder="placeholder"
      :multiple="multiple"
      :collapse-tags="multiple"
      :remote-method="keywordSearch"
      @focus="focus"
      @input="updateSelectValue"
      v-el-select-loadmore="loadMoreOptions"
    >
      <el-option
        v-for="item in options"
        :key="item.id"
        class="advanced-search__product-search-select-option"
        :label="item.name"
        :origin="item"
        :value="item"
      >
        <div class="service-template-option">
          <h3>{{ item.name }}</h3>
          <p class="service-template-option-content">
            <span class="service-template-option-content-text">
              <label>{{$t('common.fields.serialNumber.displayName')}}：</label>
              <span>{{ item.serialNumber }}</span>
            </span>
            <span class="service-template-option-content-text">
              <label>{{$t('common.fields.type.displayName')}}:</label>
              <span>{{ item.type }}</span>
            </span>
            <span class="service-template-option-content-text">
              <label>{{$t('common.fields.customer.displayName')}}：</label>
              <span>{{ item.customerName || '' }}</span>
            </span>
          </p>
        </div>
      </el-option>
    </el-select>
  </div>
</template>

<script>
import {
  defineComponent,
  ref,
  computed,
} from 'vue';
import i18n from '@src/locales';

import { debounce } from 'lodash';
import { getSystemNormalSearchInputForLength } from '@model/utils/getSystemConfig.ts'

export default defineComponent({
  name: 'product-search',
  props: {
    placeholder: {
      type: String,
      default: i18n.t('common.placeholder.selectProduct'),
    },
    remoteMethod: {
      type: Function,
    },
    multiple: {
      type: Boolean,
      default: true,
    },
    value: {
      type: [Array, Object, String], // 产品暂时只有等于 传入的 是个对象
      default: null,
    },
  },
  emits: ['update'],
  setup(props, { emit, expose }) {
    const selectValue = computed(() => {
      return Array.isArray(props.value) ? [...props.value] : props.value;
    });
    const options = ref(
      props.value
        ? Array.isArray(props.value)
          ? [...props.value]
          : [props.value]
        : []
    );
    const searchParam = ref({
      pageNum: 1,
      keyword: '',
    });
    const hasNextPage = ref(true);
    const loadMoreOptions = ref({
      disabled: false,
      callback: loadMore,
      distance: 10,
    });
    const loading = ref(false);

    // 搜索
    async function searchFn() {
      try {
        if(loading.value) return
        if (!props.remoteMethod) return console.warn('请提供产品查询方法');
        loading.value = true;
        const res = await props.remoteMethod(searchParam.value);
        if (!res || !res.list) return (options.value = []);

        if (searchParam.value.pageNum === 1) {
          options.value = [];
        }

        hasNextPage.value = !res.isLastPage;
        loadMoreOptions.value.disabled = !hasNextPage.value;
        options.value.push(...res.list);
      } catch (error) {
        options.value = [];
      }finally {
        loading.value = false;
      }
    }

    const search = debounce(searchFn, 500);

    // 关键字搜索
    function keywordSearch(keyword) {
      // 产品相关搜索受系统搜索长度控制
      searchParam.value.keyword = getSystemNormalSearchInputForLength(keyword);
      searchParam.value.pageNum = 1;
      search();
    }

    function focus() {
      emit('focus')
      if (options.value.length) return;
      keywordSearch();
    }

    // 加载更多
    function loadMore() {
      if(!hasNextPage.value || loading.value) return
      searchParam.value.pageNum++;
      search();
    }

    // 选中更新值
    function updateSelectValue(selected) {
      emit('update', selected);
    }

    const handleSetDefaultValue = async (keyword, id, customerId)=> {
      try {
        const res = await props.remoteMethod({ keyword, id, customerId });
        if (!res || !res.list) return (options.value = []);

        if (searchParam.value.pageNum === 1) {
          options.value = [];
        }

        hasNextPage.value = !res.isLastPage;
        loadMoreOptions.value.disabled = !hasNextPage.value;
        options.value.push(...res.list);
      } catch(e) {
        options.value = [];
      }
    }

    expose({
      handleSetDefaultValue,
      keywordSearch
    })

    return {
      selectValue,
      options,
      loadMoreOptions,
      focus,
      keywordSearch,
      updateSelectValue,
    };
  },
});
</script>
<style lang="scss" scoped>
.el-select-dropdown__item {
  word-break: break-all;
  white-space: normal;
  padding: 0 16px;
}
</style>>
<style lang="scss">
.el-select-dropdown__item.selected {
  p > span {
    color: $color-primary !important;
  }
}
.advanced-search__product-search-select-option {
  height: auto;
}
.service-template-option-content {
  &-text {
    display: flex;
    color: #595959 !important;

    label {
      padding-top: 0;
    }

    span {
      line-height: 24px;
    }
  }
}
</style>
